import {
	defineStore
} from 'pinia'
import {
	getUserInfo
} from '@/api/user.js';


// user
export const useUserStore = defineStore('user', {
	// state
	state: () => ({
		loginShow: false, //是否显示登录弹窗
		infoShow: false, //完善信息
		userInfo: uni.getStorageSync('userInfo') || null,
		adInfo: uni.getStorageSync('ad_info') || null
	}),

	// getters
	getters: {
		info() {
			return this.info;
		}
	},

	// action
	actions: {
		setUser(userInfo) {
			this.userInfo = userInfo;
			uni.setStorageSync('userInfo', userInfo)
		},
		setLocation(adInfo) { //设置地理信息
			let now = new Date().getTime()
			adInfo.expiresTime = now + 24 * 60 * 60 * 1000 //24小时后尝试重新获取位置信息
			this.adInfo = adInfo
			uni.setStorageSync('ad_info', adInfo)
			uni.$emit('changLocation', adInfo)
		},
		showLogin(show) { //打开登录弹窗
			this.loginShow = show
		},
		showInfo(show) { //打开登录弹窗
			this.infoShow = show
		},

		syncUserInfo(arg) { //同步用户信息
			return new Promise((resolve, reject) => {
				getUserInfo({}).then(res => {
					if (res.code == 1 && res.data) {
						// commit('setUser',res.data.list)
						this.setUser(res.data.list)
						resolve(res.data.list)
					} else {
						reject()
					}
				})
			})
		},

		loginAfterJump() {
			let pageArr = getCurrentPages()
			let curenntPage = pageArr[pageArr.length - 1]
			let tabars = ['pages/tabbar/index/index', 'pages/tabbar/shop/index', 'pages/tabbar/my/my']
			if (tabars.includes(curenntPage.route)) { //如果是tabbar 页面
				curenntPage.onLoad(curenntPage.options) //重载页面
				curenntPage.onShow()
				uni.setStorageSync('pageUrl', null)
			} else {
				if (('/' + curenntPage.route) == appOps.loginSetting.loginPath) { //判断是否为激活页面
					let u = uni.getStorageSync('pageUrl') //跳转激活页面的前一个页面
					uni.reLaunch({
						url: u,
						success() {
							uni.setStorageSync('pageUrl', null)
						}
					})
				} else { //重载页面
					curenntPage.onShow()
					curenntPage.onLoad(curenntPage.options)
					uni.setStorageSync('pageUrl', null)
				}
			}
		}


	}
})